import { Injectable } from '@angular/core';
import { BehaviorSubject, timer } from 'rxjs';
import * as cuid from 'cuid';

export enum TodoStatus {
  TODO = 'todo',
  DOING = 'doing',
  DONE = 'done'
}

export interface TodoList {
  id: string;
  text: string;
  status: TodoStatus;
}

export interface DataFlow {
  list: TodoList[];
}

@Injectable({
  providedIn: 'root'
})

export class DataFlowPracticeService {
  dataFlow: DataFlow;
  dataFlowSubject: BehaviorSubject<DataFlow>;
  constructor() {
    if (!this.dataFlow) {
      this.dataFlow = this.initFlowData();
      this.mockList(10);
    }
    this.dataFlowSubject = new BehaviorSubject<DataFlow>(this.dataFlow);
  }

  getDataFlowSubject = () => {
    this.updateData();
    return this.dataFlowSubject;
  }

  updateData = () => {
    this.dataFlowSubject.next(this.dataFlow);
  }

  add = (item: TodoList) => {
    this.dataFlow.list.push(item);
    this.updateData();
  }

  delete = (index: number) => {
    this.dataFlow.list.splice(index, 1);
    this.updateData();
  }

  initFlowData = () => ({
    list: []
  })

  mockList = (num: number) => {
    const list: TodoList[] = [];
    if (num > 0) {
      for (let i = 0; i < num; i++) {
        list.push({
          id: cuid(),
          text: `todo-${i}`,
          status: TodoStatus.TODO
        })
      }
    }
    this.dataFlow.list = list;
  }

  updateItem = (item: TodoList) => {
    this.dataFlow.list = this.dataFlow.list.map((todo: TodoList) => {
      if (todo.id === item.id) return item;
      return todo;
    });
    this.updateData();
  }

  asyncGetItemById = (id: string, callback: any) => {
    const detail = this.dataFlow.list.filter(item => item.id === id)[0];
    timer(1000).subscribe(() => { callback(detail) });
  }
}
